package com.huazi.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huazi.commonutils.CommentResult;
import com.huazi.eduservice.entity.EduCourse;
import com.huazi.eduservice.entity.EduTeacher;
import com.huazi.eduservice.service.EduCourseService;
import com.huazi.eduservice.service.EduTeacherService;
import com.huazi.eduservice.vo.TeacherQuery;
import com.huazi.eduservice.vo.Teachers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author huazi
 * @since 2021-03-12
 */
@RestController
@Api(description = "讲师管理")
//@CrossOrigin//解决跨域问题
@RequestMapping("/eduservice/edu-teacher")
public class EduTeacherController {
    @Autowired
    EduTeacherService eduTeacherService;
    @Autowired
    EduCourseService courseService;
    //查询所有讲师信息
    @GetMapping("findAll")
    @ApiOperation("所有讲师列表")
    public CommentResult selectList(){
        List<EduTeacher> list = eduTeacherService.list(null);
        if(list!=null&&list.size()<1){
            return CommentResult.getError();
        }
        Page<EduTeacher> page=new Page<>(1,list.size());
        page.setRecords(list).setSize(list.size()).setTotal(list.size()).setPages(1).setCurrent(1);
        return CommentResult.getOK().data("pageLists",page);
    }
    //查询所有讲师信息（只需要id和姓名）
    @GetMapping("findAll2")
    @ApiOperation("所有讲师列表(查询id和姓名)")
    public CommentResult selectList2(){
        List<EduTeacher> list = eduTeacherService.list(null);
        Map<String,Object> map=new ConcurrentHashMap<>();
        for (EduTeacher edu: list
             ) {
           map.put(String.valueOf(edu.getId()),edu.getName());
        }
//        System.out.println("teachers");
        return CommentResult.getOK().data("teachers",map);
    }
    //逻辑删除讲师方法
    @ApiOperation("逻辑删除讲师")
    @DeleteMapping("delete/{id}")
    public CommentResult remove(@ApiParam(name="id",value = "讲师Id",required = true) @PathVariable Integer id){
        EduTeacher byId = eduTeacherService.getById(id);//查询数据库有没有此id
        if(byId!=null){//有就进行删除
            boolean b = eduTeacherService.removeById(id);
            return CommentResult.getOK().data("message","删除成功！");
        }
        //没有就返回错误消息
        return CommentResult.getError().data("message","删除失败！").setMsg("delete");
    }

    //分页获取讲师信息
    @ApiOperation("分页讲师信息")
    @GetMapping("pageTeacher/{current}/{size}")
    public CommentResult pageTeacher(@ApiParam(name="current",value = "当前页",required = true) @PathVariable Integer current,@ApiParam(name="size",value = "页面记录数",required = true) @PathVariable Integer size){
        Page<EduTeacher> page=new Page<>(current,size);//创建对象分页
        eduTeacherService.page(page,null);
        return getOkByError(page);
    }
    //组合条件分页获取讲师信息
    @ApiOperation("组合条件分页查询讲师")
    @PostMapping("pageWrapperTeacher/{current}/{size}")
    public CommentResult pageWrapperTeacher(
            @ApiParam(name="current",value = "当前页",required = true)
            @PathVariable Integer current,
            @ApiParam(name="size",value = "页面记录数",required = true)
            @PathVariable Integer size,
            @RequestBody(required = false) TeacherQuery teacherQuery){//表示对象可以没有数据
        Page<EduTeacher> page=new Page<>(current,size);//创建对象分页
        QueryWrapper<EduTeacher> wrapper=new QueryWrapper<>();
        //获取条件值
        String name = teacherQuery.getName();
        Integer level = teacherQuery.getLevel();
        LocalDateTime start = teacherQuery.getStartTime();
        LocalDateTime end = teacherQuery.getEndTime();
        //判断是否构成条件
        if(!StringUtils.isEmpty(name)) wrapper.like("name",name);

        if(!StringUtils.isEmpty(level)) wrapper.eq("level",level);

        if(!StringUtils.isEmpty(start)) wrapper.ge("gmt_create",start);

        if(!StringUtils.isEmpty(end)) wrapper.le("gmt_create",end);

        eduTeacherService.page(page,wrapper);

        return getOkByError(page);
    }

    //添加讲师
    @ApiOperation("添加讲师")
    @PostMapping("addTeacher")
    public CommentResult addTeacher(@RequestBody EduTeacher eduTeacher){
        try{
            boolean save = eduTeacherService.save(eduTeacher);
            if(save) return CommentResult.getOK();
            return CommentResult.getError().setMsg("add");
        }catch (Exception e){
            return CommentResult.getError().setMsg("add");
        }
    }
    //根据姓名查询信息
    @ApiOperation("姓名查询讲师")
    @GetMapping("queryByName/{name}")
    public CommentResult queryByName( @ApiParam(name = "name",value = "讲师名称",required = true) @PathVariable("name") String name){
        EduTeacher byId = eduTeacherService.getOne(new QueryWrapper<EduTeacher>().eq("name",name));
        if(byId!=null) return CommentResult.getOK().setMsg("yes").data("info",true);
        return CommentResult.getOK().setMsg("no").data("info",false);
    }
    //根据Id查询讲师
    @ApiOperation("id查询讲师")
    @GetMapping("queryOneTeacher/{id}")
    public CommentResult queryOneTeacher( @ApiParam(name = "id" ,value = "讲师Id",required = true) @PathVariable("id") Integer id){
        EduTeacher byId = eduTeacherService.getById(id);
        if(byId!=null) return CommentResult.getOK().data("teacher",byId);
        return CommentResult.getError();
    }
    //修改讲师
    @ApiOperation("修改讲师信息")
    @PostMapping("updateTeacher")
    public CommentResult updateTeacher(@RequestBody EduTeacher eduTeacher){
        boolean b = eduTeacherService.updateById(eduTeacher);
        if(b) return CommentResult.getOK().data("update",b);
        return CommentResult.getError().setMsg("update");
    }
    //测试异常方法
    @ApiOperation("测试异常方法")
    @GetMapping("testException")
    public CommentResult testException(){
        int i=10/0;
        return CommentResult.getError();
    }
    public CommentResult getOkByError(Page<EduTeacher> page ){
        if(page.getRecords()!=null&&page.getRecords().size()>0){
            return CommentResult.getOK().data("pageLists",page);
        }
        page.setCurrent(0).setPages(0).setRecords(new ArrayList<>()).setSize(0).setTotal(0);
        //如果没有数据则返回空数据
        return CommentResult.getError().data("pageLists",page);
    }
    //-------------前端获取数据------------------
    //前端获取前4个讲师信息(首页显示)
    @GetMapping("getIndexTeachers/{current}/{size}")
    public CommentResult getIndexTeachers(@PathVariable("current") Integer current,@PathVariable("size") Integer size){
        CommentResult indexTeacher = eduTeacherService.getIndexTeachers(current, size);
        System.out.println("4--");
        return indexTeacher;
    }
    //分页获取讲师信息（讲师列表）
    //获取前8个讲师信息
    @GetMapping("getTeacherLists/{current}/{size}")
    public CommentResult getTeacherLists(@PathVariable("current") Integer current,@PathVariable("size") Integer size){
        CommentResult teacherLists = eduTeacherService.getTeacherLists(current, size);
        return teacherLists;
    }
    //讲师详情信息(基本信息和所讲课程)
    @GetMapping("getTeacherInfo/{id}")
    public CommentResult getTeacherInfo(@PathVariable("id") Integer id){
        //获取讲师信息
        EduTeacher teacher = eduTeacherService.getById(id);
        //获取讲师所讲的课程
        List<EduCourse> courses = courseService.list(new QueryWrapper<EduCourse>().eq("teacher_id", id));
//        Page<EduCourse> page=new Page<>();
//        page.setRecords(courses);
        return CommentResult.getOK().data("teacher",teacher).data("courses",courses);
    }

}

